<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
  import { getUploadAPI, orderDetailAPI } from '@/api/consult'
  import { useUserStore } from '@/stores/user'
  import { onLoad } from '@dcloudio/uni-app'
  import { io, type Socket } from 'socket.io-client'

  // 导入🧍各个小组件
  import RoomStatus from './components/room-status.vue'
  import PatientInfo from './components/patient-info.vue'
  import NotifyInfo from './components/notify-info.vue'
  import MessageInfo from './components/message-info.vue'
  import PrescriptionInfo from './components/prescription-info.vue'
  import RoatInfo from './components/rate-info.vue'
  import { nextTick, ref } from 'vue'
  import type { OrderDetail } from '@/type/consult'
  import type { Datum, MsgItem } from '@/type/room'

  //
  import COS from 'cos-js-sdk-v5'

  const props = defineProps<{ orderId: string; payResult: string }>()
  const store = useUserStore()
  const msgList = ref<MsgItem[]>([])
  // 挪出socket ，作用域问题
  let socket: Socket
  onLoad(() => {
    if (props.payResult === 'false') {
      uni.switchTab({ url: 'pages/my/my' })
      return
    }
    socket = io('https://consult-api.itheima.net', {
      auth: { token: 'Bearer ' + store.token },
      query: { orderId: props.orderId },
      transports: ['websocket', 'polling'],
      timeout: 5000,
    })
    socket.on('connect', () => {
      console.log('连接成功')
    })
    // 服务器发来的消息statusChange
    socket.on('statusChange', (res) => {
      console.log('res  ----->  ', res)
      getOrederInfo()
    })

    // 监听历史聊天消息

    socket.on('chatMsgList', (res) => {
      console.log('历史消息', res)
      if (res.code !== 10000) return
      res.data.forEach((item: Datum) => {
        msgList.value.push(
          { msgType: 31, msg: { content: item.createTime }, id: item.createTime },
          ...item.items!
        )
      })
      nextTick(() => {
        lastId.value = 'xxx' + (msgList.value.length - 1)
      })
    })

    // 监听新消息
    socket.on('receiveChatMsg', (res) => {
      console.log('新消息', res)
      msgList.value.push(res)
      nextTick(() => {
        lastId.value = 'xxx' + (msgList.value.length - 1)
      })
    })
  })

  // 查询订单中患者的信息
  const orderInfo = ref({} as OrderDetail)
  const getOrederInfo = async () => {
    const res = await orderDetailAPI(props.orderId)
    orderInfo.value = res
  }

  onLoad(() => {
    getOrederInfo()
  })

  // 发送消息逻辑
  const contentText = ref('')
  const onSendText = () => {
    socket.emit('sendChatMsg', {
      // 发送人Id
      from: store.userId,
      // 接收人(医生)Id
      to: orderInfo.value.docInfo.id,
      // 消息类型
      msgType: 1,
      // 消息内容
      msg: {
        content: contentText.value,
      },
    })
    contentText.value = ''
  }
  // 发送图片消息
  const onSendImage = async () => {
    if (orderInfo.value?.status !== 3) {
      uni.showToast({
        title: '医生不在线',
        icon: 'none',
      })
      return
    }
    const res = await uni.chooseImage({ count: 1 })
    const data = await getUploadAPI(res.tempFilePaths[0])
    socket.emit('sendChatMsg', {
      // 发送人Id
      from: store.userId,
      // 接收人(医生)Id
      to: orderInfo.value.docInfo.id,
      // 图片消息类型
      msgType: 4,
      // 图片内容
      msg: {
        picture: {
          id: data.id,
          url: data.url,
        },
      },
    })
    // 打通上传的逻辑
  //   const cos = new COS({
  //     SecretId: 'AKIDwlNuFNHmIdp1B8rPltnaBpMkvyseHrDP', // sts服务下发的临时 secretId
  //     SecretKey: '81kGXbS8aopeMs0vgDlHetyrX5RaXN1c', // sts服务下发的临时 secretKey
  //   })
  //   const res2 = await uni.chooseVideo()
  //   console.log('res  ----->  ', res2.tempFile)
  //   cos.uploadFile(
  //     {
  //       Bucket: 'xigua-1333988420' /* 填写自己的 bucket，必须字段 */,
  //       Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
  //       Key: 'xxx.mp4' /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */,
  //       Body: res2.tempFile, // 上传文件对象
  //       onProgress: function (progressData) {
  //         console.log(JSON.stringify(progressData))
  //       },
  //     },
  //     function (err, data) {
  //       if (err) {
  //         console.log('上传失败', err)
  //       } else {
  //         console.log('上传成功', 'https://' + data.Location)

  //         socket.emit('sendChatMsg', {
  //           // 发送人Id
  //           from: store.userId,
  //           // 接收人(医生)Id
  //           to: orderInfo.value.docInfo.id,
  //           // 图片消息类型
  //           msgType: 4,
  //           // 图片内容
  //           msg: {
  //             picture: {
  //               id: 'xxx',
  //               url: 'https://' + data.Location,
  //             },
  //           },
  //         })
  //       }
  //     }
  //   )
  }
  // 滚动到最后的消息
  const lastId = ref('')
</script>

<template>
  <view class="room-page">
    <!-- 咨询室小组件状态 -->
    <RoomStatus
      :status="orderInfo.status"
      :status-value="orderInfo.statusValue"
      :countdown="orderInfo.countdown"
    />
    <scroll-view
      scroll-with-animation
      :scroll-into-view="lastId"
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
    >
      <view class="message-container">
        <!-- 此处将来填充更多代码... -->
        <view v-for="(item, index) in msgList" :key="item.id" :id="'xxx' + index">
          <PatientInfo :info="item.msg?.consultRecord" v-if="item.msgType === 21" />
          <NotifyInfo v-if="item.msgType!>=31" :type="item.msgType!">
            {{ item.msg?.content?.trim() }}
          </NotifyInfo>
          <MessageInfo
            :type="item.msgType"
            :info="item"
            v-if="item.msgType === 1 || item.msgType === 4"
          />
          <PrescriptionInfo v-if="item.msgType === 22" :info="item.msg!" />

          <RoatInfo
            v-if="item.msgType === 23 || item.msgType === 24"
            :info="item.msg!"
            :order-id="orderId"
            :doctor-id="orderInfo.docInfo.id"
            :type="item.msgType"
          />
        </view>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          @confirm="onSendText"
          v-model="contentText"
          :disabled="orderInfo.status !== 3"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button">
          <uni-icons size="40" color="#979797" type="image" @click="onSendImage"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
  @import './room.scss';
</style>
